// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2012 The cwkshell Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cuc/src/cwkshell/browser/shell_browser_main_parts.h"


#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "base/string_number_conversions.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "cuc/src/cwkshell/browser/shell_browser.h"
#include "cuc/src/cwkshell/view/shell_browser_window.h"
#include "cuc/src/cwkshell/browser/shell_browser_context.h"
#include "cuc/src/cwkshell/browser/shell_devtools_delegate.h"
#include "cuc/src/cwkshell/common/cwkshell_switches.h"
#include "googleurl/src/gurl.h"
#include "grit/net_resources.h"
#include "net/base/net_module.h"
#include "ui/base/resource/resource_bundle.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "ui/views/focus/accelerator_handler.h"


#if defined(USE_AURA)
#include "ui/aura/desktop/desktop_screen.h"
#include "ui/aura/desktop/desktop_stacking_client.h"
#include "ui/aura/env.h"

#include "ui/aura/single_display_manager.h"

#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_native_widget_helper_aura.h"
#include "ui/views/widget/native_widget_aura.h"
#endif

namespace cuc {
	namespace shell {

		namespace {


			static GURL GetStartupURL() {
				CommandLine* command_line = CommandLine::ForCurrentProcess();
				
				const CommandLine::StringVector& args = command_line->GetArgs();

#if defined(OS_ANDROID)
				// Delay renderer creation on Android until surface is ready.
				return GURL();
#endif

				if (args.empty())
					return GURL("http://www.google.com/");

				GURL url(args[0]);
				if (url.is_valid() && url.has_scheme())
					return url;

				return net::FilePathToFileURL(base::FilePath(args[0]));
			}

			base::StringPiece PlatformResourceProvider(int key) {
				if (key == IDR_DIR_HEADER_HTML) {
					base::StringPiece html_data =
						ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
						IDR_DIR_HEADER_HTML);
					return html_data;
				}
				return base::StringPiece();
			}

		}  // namespace

		ShellBrowserMainParts::ShellBrowserMainParts(
			const content::MainFunctionParams& parameters)
			: BrowserMainParts(),
			parameters_(parameters),
			run_message_loop_(true),
			devtools_delegate_(NULL){
		}

		ShellBrowserMainParts::~ShellBrowserMainParts() {
		}

		void ShellBrowserMainParts::PreEarlyInitialization() 
		{

		}

		void ShellBrowserMainParts::PreMainMessageLoopStart() 
		{

		}

		void ShellBrowserMainParts::PostMainMessageLoopStart() 
		{

		}
		void ShellBrowserMainParts::PreMainMessageLoopRun() {
			browser_context_.reset(new ShellBrowserContext(false));
			
			off_the_record_browser_context_.reset(new ShellBrowserContext(true));
			
			shell_browser_ = new ShellBrowser( browser_context_.get());

			shell_browser_->CreateContanier(browser_context_.get(),
				shell_browser_->GetShellProperty()->GetHomePageUrl(),
				NULL,
				MSG_ROUTING_NONE,
				NULL);

			net::NetModule::SetResourceProvider(PlatformResourceProvider);

			int port = 0;


			const CommandLine& command_line = *CommandLine::ForCurrentProcess();
			if (command_line.HasSwitch(cuc::switches::kRemoteDebuggingPort)) {
				int temp_port;
				std::string port_str =
					command_line.GetSwitchValueASCII(cuc::switches::kRemoteDebuggingPort);
				if (base::StringToInt(port_str, &temp_port) &&
					temp_port > 0 && temp_port < 65535) {
						port = temp_port;
				} else {
					DLOG(WARNING) << "Invalid http debugger port number " << temp_port;
				}
			}

			devtools_delegate_ = new ShellDevToolsDelegate(browser_context_.get(), port);


		if (parameters_.ui_task) {
			parameters_.ui_task->Run();
			delete parameters_.ui_task;
			run_message_loop_ = false;
		}
				LOG(INFO)<<" ShellBrowserMainParts::PreMainMessageLoopRun()";
		}

		void ShellBrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_AURA)
			Shell::PlatformExit();
#endif
			if (devtools_delegate_)
				devtools_delegate_->Stop();
			browser_context_.reset();
			off_the_record_browser_context_.reset();
		}

		bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) {
			// xxx: Hax here because this kills event handling.
		
			views::AcceleratorHandler accelerator_handler;
			base::RunLoop run_loop(&accelerator_handler);
			run_loop.Run();
			
			return true;

			//return !run_message_loop_;
		}

	}  // namespace shell
}  // namespace cuc
